import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'

// 获取任务列表
export async function GET(request: NextRequest) {
  try {
    const user = await getUserFromRequest(request)

    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const tasks = await prisma.extractionTask.findMany({
      orderBy: { createdAt: 'desc' },
      include: {
        creator: {
          select: {
            username: true
          }
        },
        executions: {
          orderBy: { createdAt: 'desc' },
          take: 10,
          select: {
            id: true,
            status: true,
            startedAt: true,
            completedAt: true,
            videosFound: true,
            videosExtracted: true
          }
        }
      }
    })

    return NextResponse.json({
      tasks
    })

  } catch (error) {
    console.error('Get tasks error:', error)
    return NextResponse.json(
      { error: '获取任务列表失败' },
      { status: 500 }
    )
  }
}

// 创建新任务
export async function POST(request: NextRequest) {
  try {
    const user = await getUserFromRequest(request)
    console.log('获取到的用户:', JSON.stringify(user, null, 2))

    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    // 临时修复：如果用户对象没有id，使用默认值1（admin用户）
    const userId = user.id || 1
    console.log('使用的用户ID:', userId)

    const { name, keywords, maxCount, isRecurring, interval, autoExtractText, autoDownloadFiles } = await request.json()

    if (!name || !keywords || !maxCount) {
      return NextResponse.json(
        { error: '任务名称、关键词和提取数量不能为空' },
        { status: 400 }
      )
    }

    // 验证关键词格式
    let keywordsArray
    try {
      keywordsArray = JSON.parse(keywords)
      if (!Array.isArray(keywordsArray) || keywordsArray.length === 0) {
        throw new Error('关键词格式错误')
      }
    } catch (error) {
      return NextResponse.json(
        { error: '关键词格式错误，请提供有效的JSON数组' },
        { status: 400 }
      )
    }

    // 创建任务
    const task = await prisma.extractionTask.create({
      data: {
        name,
        keywords,
        maxCount: parseInt(maxCount),
        isRecurring: Boolean(isRecurring),
        interval: isRecurring ? parseInt(interval || 24) : null,
        autoDownloadFiles: Boolean(autoDownloadFiles),
        autoExtractText: Boolean(autoExtractText),
        createdBy: userId,
        nextRunAt: isRecurring ? new Date() : null
      },
      include: {
        creator: {
          select: {
            username: true
          }
        }
      }
    })

    return NextResponse.json({
      message: '任务创建成功',
      task
    })

  } catch (error) {
    console.error('Create task error:', error)
    return NextResponse.json(
      { error: '创建任务失败' },
      { status: 500 }
    )
  }
}
